package com.example.sharesinfo.fragment;


import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.ScrollablePanelAdapter;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.bean.OptionalStockBean;
import com.example.sharesinfo.bean.StockDetailBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.manager.DialogManager;
import com.example.sharesinfo.model.ColumnTitle;
import com.example.sharesinfo.model.DataInfo;
import com.example.sharesinfo.model.OptionalStockModel;
import com.example.sharesinfo.model.StockInfo;
import com.example.sharesinfo.ui.SharesInfoActivity;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.DialogView;
import com.example.sharesinfo.view.SearchFragment;
import com.google.gson.Gson;
import com.kelin.scrollablepanel.library.ScrollablePanel;
import com.wyt.searchbox.custom.IOnSearchClickListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class OptionalFragment extends BaseFragment implements View.OnClickListener {
    private static final String LOGTAG = "OptionalFragment:";
    private static final int QUERYDATASUCCESS = 2001;
    private static final int QUERYDATAEMPTY = 2002;
    private static final int QUERYSTOCKSUCCESS = 2003;
    private static final int QUERYSTOCKEMPTY = 2004;
    private static final int ADDSTOCKSUCCESS = 2005;
    private static final int ADDSTOCKFailed = 2006;
    private static final int DELSTOCKSUCCESS = 2007;
    private static final int DELSTOCKFailed = 2008;
    private ScrollablePanel sp_data;
    private ScrollablePanelAdapter spAdapter;
    private List<OptionalStockModel> mList = new ArrayList<>();
    private OptionalFragment fa;
    private ImageButton ib_search;
    private LinearLayout ll_add_stock;
    //搜索框
    private SearchFragment searchFragment;
    //股票简介
    private DialogView mStockDialog;
    private ImageView ib_return;
    private TextView iv_stock_name;
    private TextView stock_code;
    private TextView stock_value;
    private TextView stock_trade;
    private LinearLayout ll_add;
    //删除弹框
    private DialogView mDeleteDialog;
    private TextView tv_delete;
    private TextView tv_cancel;
    private int OptionalStockId;
    private int mRow;

    public OptionalFragment getFragment() {
        if (fa == null) {
            fa = new OptionalFragment();
        }
        return fa;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    //有数据
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    OptionalStockBean result = (OptionalStockBean) msg.obj;
                    for (int i = 0; i < result.getData().size(); i++) {
                        OptionalStockModel model = new OptionalStockModel();
                        model.setId(result.getData().get(i).getId());
                        model.setStockCode(result.getData().get(i).getStockCode());
                        model.setStockName(result.getData().get(i).getStockName());
                        model.setStockPinyin(result.getData().get(i).getStockPinyin());
                        model.setStockValue(result.getData().get(i).getStockValue());
                        model.setStockType(result.getData().get(i).getStockType());
                        model.setStockExchange(result.getData().get(i).getStockExchange());
                        model.setStockTendency(result.getData().get(i).getStockTendency());
                        model.setNowPrice(result.getData().get(i).getNowPrice());
                        model.setDiff_Rate(result.getData().get(i).getDiff_Rate());
                        model.setDiff_Money(result.getData().get(i).getDiff_Money());
                        model.setSwing(result.getData().get(i).getSwing());
                        model.setOpenPrice(result.getData().get(i).getOpenPrice());
                        model.setYesterdayClosePrice(result.getData().get(i).getYesterdayClosePrice());
                        model.setTodayMax(result.getData().get(i).getTodayMax());
                        model.setTodayMin(result.getData().get(i).getTodayMin());
                        model.setTurnover(result.getData().get(i).getTurnover());
                        model.setPe(result.getData().get(i).getPe());
                        model.setPb(result.getData().get(i).getPb());
                        model.setAppointRate(result.getData().get(i).getAppointRate());
                        mList.add(model);
                    }
                    generateData(mList);
                    break;
                case QUERYDATAEMPTY:
                    //没有数据
                    break;
                case QUERYSTOCKSUCCESS:
                    //查询股票成功
                    StockDetailBean result1 = (StockDetailBean) msg.obj;
                    iv_stock_name.setText(result1.getData().get(0).getName());
                    stock_code.setText(result1.getData().get(0).getCode());
                    stock_value.setText(result1.getData().get(0).getAll_value());
                    stock_trade.setText(result1.getData().get(0).getTradeAmount());
                    DialogManager.getInstance().show(mStockDialog);
                    break;
                case QUERYSTOCKEMPTY:
                    //查询股票失败
                    Toast.makeText(getContext(), "请输入正确的股票代码如：000001", Toast.LENGTH_SHORT).show();
                    break;
                case ADDSTOCKSUCCESS:
                    //添加股票成功
                    Toast.makeText(getContext(), "添加股票成功", Toast.LENGTH_SHORT).show();
                    queryDatas();
                    DialogManager.getInstance().hide(mStockDialog);
                    break;
                case ADDSTOCKFailed:
                    //添加股票失败
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    DialogManager.getInstance().hide(mStockDialog);
                    break;
                case DELSTOCKSUCCESS:
                    Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                    queryDatas();
                    DialogManager.getInstance().hide(mDeleteDialog);
                    break;
                case DELSTOCKFailed:
                    Toast.makeText(getContext(), "删除失败", Toast.LENGTH_SHORT).show();
                    DialogManager.getInstance().hide(mDeleteDialog);
                    break;
                case 404:
                    //访问错误
                    Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
                    break;
            }

            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_optional, null);
        initView(view);
        initDeleteStockDialog();
        initStockResultDialog();
        queryDatas();
        initData();
        return view;
    }

    private void initData() {
        initTitle();
    }

    private void generateData(List<OptionalStockModel> list) {
        List<StockInfo> stockInfoList = new ArrayList<>();
        List<List<DataInfo>> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            OptionalStockModel model = list.get(i);
            StockInfo stockInfo = new StockInfo();
            stockInfo.setStockName(model.getStockName());

            stockInfo.setRoomId(i);
            stockInfo.setStockId(model.getStockCode());
            stockInfoList.add(stockInfo);
            addData(model, dataList);

        }
        spAdapter.setStockInfoList(stockInfoList);
        spAdapter.setDataList(dataList);
        sp_data.notifyDataSetChanged();
    }

    private void initTitle() {
        List<ColumnTitle> columnTitleList = new ArrayList<>();
        String column1 = "最新";
        String column2 = "涨跌额";
        String column3 = "涨跌幅";
        String column4 = "今开";
        String column5 = "最高";
        String column6 = "最低";
        String column7 = "市盈率";
        String column8 = "市净率";
        String column9 = "换手率";

        ColumnTitle columnTitle1 = new ColumnTitle();
        columnTitle1.setColumnTitle(column1);
        columnTitleList.add(columnTitle1);

        ColumnTitle columnTitle2 = new ColumnTitle();
        columnTitle2.setColumnTitle(column2);
        columnTitleList.add(columnTitle2);

        ColumnTitle columnTitle3 = new ColumnTitle();
        columnTitle3.setColumnTitle(column3);
        columnTitleList.add(columnTitle3);

        ColumnTitle columnTitle4 = new ColumnTitle();
        columnTitle4.setColumnTitle(column4);
        columnTitleList.add(columnTitle4);
        ColumnTitle columnTitle5 = new ColumnTitle();
        columnTitle5.setColumnTitle(column5);
        columnTitleList.add(columnTitle5);
        ColumnTitle columnTitle6 = new ColumnTitle();
        columnTitle6.setColumnTitle(column6);
        columnTitleList.add(columnTitle6);

        ColumnTitle columnTitle7 = new ColumnTitle();
        columnTitle7.setColumnTitle(column7);
        columnTitleList.add(columnTitle7);

        ColumnTitle columnTitle8 = new ColumnTitle();
        columnTitle8.setColumnTitle(column8);
        columnTitleList.add(columnTitle8);

        ColumnTitle columnTitle9 = new ColumnTitle();
        columnTitle8.setColumnTitle(column9);
        columnTitleList.add(columnTitle9);

        spAdapter.setColumnTitleList(columnTitleList);
    }

    private void initView(View view) {
        sp_data = view.findViewById(R.id.sp_data);
        spAdapter = new ScrollablePanelAdapter(0, new ScrollablePanelAdapter.OnBindDataListener() {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, final int row, int column) {
                int viewType = spAdapter.getItemViewType(row, column);
                switch (viewType) {
                    case ScrollablePanelAdapter.COLUMN_TITLE_TYPE:
                        spAdapter.setColumnTitleView(column, (ScrollablePanelAdapter.ColumnTitleViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.STOCK_TYPE:
                        spAdapter.setStockView(row, (ScrollablePanelAdapter.StockViewHolder) holder);
                        holder.itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                SharesInfoActivity.startActivity(getContext(), mList.get(row - 1).getStockCode());
                            }
                        });
                        break;
                    case ScrollablePanelAdapter.DATA_TYPE:
                        spAdapter.setDataView(row, column, (ScrollablePanelAdapter.DataViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.TITLE_TYPE:
                        break;
                }

            }
        });
        sp_data.setPanelAdapter(spAdapter);
        ll_add_stock = view.findViewById(R.id.ll_add_stock);
        ll_add_stock.setOnClickListener(this);
        searchFragment = SearchFragment.newInstance();
        searchFragment.setOnSearchClickListener(new IOnSearchClickListener() {
            @Override
            public void OnSearchClick(String keyword) {
                //这里处理逻辑
                queryStock(keyword);
            }
        });
        ib_search = view.findViewById(R.id.ib_search);
        ib_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                assert getFragmentManager() != null;
                searchFragment.show(getFragmentManager(), SearchFragment.TAG);
            }
        });
    }

    private void addData(OptionalStockModel model, List<List<DataInfo>> dataList) {
        List<DataInfo> dataInfoList = new ArrayList<>();
        DataInfo dataInfo1 = new DataInfo();
        dataInfo1.setData(model.getNowPrice());
        dataInfoList.add(dataInfo1);

        DataInfo dataInfo2 = new DataInfo();
        dataInfo2.setData(model.getDiff_Money());
        dataInfoList.add(dataInfo2);

        DataInfo dataInfo3 = new DataInfo();
        dataInfo3.setData(model.getDiff_Rate());
        dataInfoList.add(dataInfo3);

        DataInfo dataInfo4 = new DataInfo();
        dataInfo4.setData(model.getOpenPrice());
        dataInfoList.add(dataInfo4);

        DataInfo dataInfo5 = new DataInfo();
        dataInfo5.setData(model.getTodayMax());
        dataInfoList.add(dataInfo5);

        DataInfo dataInfo6 = new DataInfo();
        dataInfo6.setData(model.getTodayMin());
        dataInfoList.add(dataInfo6);

        DataInfo dataInfo7 = new DataInfo();
        dataInfo7.setData(model.getPe());
        dataInfoList.add(dataInfo7);

        DataInfo dataInfo8 = new DataInfo();
        dataInfo8.setData(model.getPb());
        dataInfoList.add(dataInfo8);

        DataInfo dataInfo9 = new DataInfo();
        dataInfo9.setData(model.getTurnover());
        dataInfoList.add(dataInfo9);

        dataList.add(dataInfoList);
    }

    /**
     * 查询自选股
     * 参数：UserId：用户id
     */

    private void queryDatas() {
        String url = "http://119.23.221.142/api/stock/GetOptionalStockList?UserId=" +
                SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i(LOGTAG + "用户id" + SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();


            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    OptionalStockBean bean = new Gson().fromJson(s, OptionalStockBean.class);
                    message.what = QUERYDATASUCCESS;
                    message.obj = bean;
                    mHandler.sendMessage(message);

                } else {
                    LogUtils.i(LOGTAG + "为空");
                    message.what = QUERYDATAEMPTY;
                    mHandler.sendMessage(message);
                }

            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });

    }

    /**
     * 根据股票代码查询股票信息
     * 参数：NameorCode：股票代码
     */
    private void queryStock(String keyword) {
        String url = "http://119.23.221.142/api/stock/GetOneStockDetail?NameorCode=" + keyword + "&userId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    StockDetailBean bean = new Gson().fromJson(s, StockDetailBean.class);
                    message.what = QUERYSTOCKSUCCESS;
                    message.obj = bean;
                    mHandler.sendMessage(message);
                } else {
                    message.what = QUERYSTOCKEMPTY;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    /**
     * 初始化删除股票弹框
     */
    private void initDeleteStockDialog() {
        mDeleteDialog = DialogManager.getInstance().initView(getContext(), R.layout.dialog_delete, Gravity.BOTTOM);
        tv_delete = mDeleteDialog.findViewById(R.id.tv_delete);
        tv_cancel = mDeleteDialog.findViewById(R.id.tv_cancel);
        tv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteOptionalStock();
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mDeleteDialog);
            }
        });
    }

    /**
     * 初始化搜索股票弹框
     */

    private void initStockResultDialog() {
        mStockDialog = DialogManager.getInstance().initView(getContext(), R.layout.dialog_stock_result, Gravity.CENTER);
        ib_return = mStockDialog.findViewById(R.id.ib_return);
        ib_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mStockDialog);
            }
        });
        iv_stock_name = mStockDialog.findViewById(R.id.iv_stock_name);
        stock_code = mStockDialog.findViewById(R.id.stock_code);
        stock_value = mStockDialog.findViewById(R.id.stock_value);
        stock_trade = mStockDialog.findViewById(R.id.stock_trade);
        ll_add = mStockDialog.findViewById(R.id.ll_add);
        ll_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addOptionalStock(stock_code.getText().toString());
            }
        });
    }

    /**
     * 添加自选股
     * 参数：Code：股票代码
     * UserId：用户id
     */

    private void addOptionalStock(String stock_code) {
        String urlRoot = "http://119.23.221.142/api/stock/AddOptionalStock?";
        Map<String, String> datas = new HashMap<>();
        datas.put("Code", stock_code);
        //LogUtils.i(LOGTAG + "用户id" + SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID, ""));
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        if (object.getString("code").equals("200")) {
                            LogUtils.i(LOGTAG + "添加成功");
                            message.what = ADDSTOCKSUCCESS;
                            mHandler.sendMessage(message);
                        } else {
                            LogUtils.i(LOGTAG + "添加失败");
                            message.what = ADDSTOCKFailed;
                            message.obj = object.getString("message");
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void OnFailed(String s) {
                        message.what = 404;
                        mHandler.sendMessage(message);
                    }
                });
    }

    /**
     * 删除自选股
     * 参数：OptionalStockId：对应自选股id
     */
    private void deleteOptionalStock() {
        String urlRoot = "http://119.23.221.142/api/stock/DeleteOptionalStock?";
        Map<String, String> datas = new HashMap<>();
        datas.put("OptionalStockId", String.valueOf(OptionalStockId));
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        if (object.getString("code").equals("200")) {
                            message.what = DELSTOCKSUCCESS;
                            mHandler.sendMessage(message);
                        } else {
                            message.what = DELSTOCKFailed;
                            message.obj = object.getString("message");
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void OnFailed(String s) {
                        message.what = 404;
                        message.obj = s;
                        mHandler.sendMessage(message);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_add_stock:
                searchFragment.show(getFragmentManager(), SearchFragment.TAG);
                break;
        }
    }
}
